package com.cd.song.api.impl;

import com.cd.common.jpa.domain.ExternalConfig;
import com.cd.common.jpa.repo.ExternalConfigRepo;
import com.cd.song.api.SongService;
import com.cd.song.jpa.domain.Song;
import com.cd.song.jpa.repo.SongRepo;
import com.cd.song.mapper.SongMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SongServiceImpl implements SongService {

    private static final Logger logger = LoggerFactory.getLogger(SongServiceImpl.class);

    @Autowired
    private SongRepo songRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private ExternalConfigRepo externalConfigRepo;

    @Override
    public List<Song> findAll(Song song) {
        return songMapper.findSongs(song);
    }

    @Override
    public Optional<Song> findById(Long id) {
        return songRepository.findById(id);
    }

    @Override
    public Song save(Song song) {
        return songRepository.save(song);
    }

    @Override
    public void deleteById(Long id) {
        songRepository.deleteById(id);
    }

    /**
     * @Description 从磁盘加载列表
     * @Author lqq
     * @Date 2025/5/31 9:38
     **/
    @Override
    public void loadMusicListWithDisk() {
        String diskPath = externalConfigRepo.findByName("song.disk.path").getValue();
        logger.info("执行加载的路径为：{}", diskPath);

        //io流获取所有列表 F:\CloudMusic
        List<Song> diskSongList = readSongsFromDisk(diskPath);
        logger.info("共找到{}条曲目", diskSongList.size());

        //数据库
        List<Song> dbSongList = songRepository.findAll();

        //比较(只考虑增量的)
        List<Song> incrementSongList = compare(dbSongList, diskSongList);
        logger.info("本次新增{}首曲目", incrementSongList.size());

        //插入
        songRepository.saveAll(incrementSongList);
    }

    /**
     * @Description 比较、仅考虑增量
     * @Author lqq
     * @Date 2025/5/31 9:38
     **/
    private List<Song> compare(List<Song> dbSongList, List<Song> diskSongList) {
        List<Song> songList = new LinkedList<>();
        //构建数据库歌曲的 Map: key = title+artist, value = Song
        Map<String, Song> dbSongMap = dbSongList.stream()
                .collect(Collectors.toMap(
                        song -> composeKey(song.getTitle(), song.getArtist()),
                        song -> song
                ));
        // 4. 遍历磁盘歌曲，进行比对并处理新增/更新
        for (Song diskSong : diskSongList) {
            String key = composeKey(diskSong.getTitle(), diskSong.getArtist());
            Song dbSong = dbSongMap.get(key);

            if (dbSong == null) {
                // 新增：数据库中没有该歌曲
                logger.info("新增歌曲: {} - {}", diskSong.getTitle(), diskSong.getArtist());
                songList.add(diskSong);
                //songRepository.save(diskSong);
            } else {
                // 判断是否需要更新
//                if (shouldUpdate(dbSong, diskSong)) {
//                    logger.info("更新歌曲: {} - {}", diskSong.getTitle(), diskSong.getArtist());
//                    updateSong(dbSong, diskSong);
//                    songRepository.save(dbSong);
//                }
            }
        }
        return songList;
    }

    //从磁盘读取列表
    private List<Song> readSongsFromDisk(String diskPath) {
        File musicDir = new File(diskPath);
        List<Song> songs = new LinkedList<>();

        if (musicDir.exists() && musicDir.isDirectory()) {
            File[] files = musicDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".mp3"));
            if (files != null) {
                for (File file : files) {
                    String fileName = file.getName();
                    String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));

                    // 按 "-" 分割艺术家和标题
                    String[] parts = fileNameWithoutExt.split(" - ");
                    if (parts.length >= 2) {
                        String rawArtist = parts[0].trim();
                        String title = parts[1].trim();

                        // 创建 Song 对象
                        Song song = new Song();
                        song.setTitle(title);
                        song.setArtist(rawArtist);

                        songs.add(song);
                    } else {
                        System.out.println("无法解析文件名: " + fileName);
                    }
                }
            }
        } else {
            System.err.println("音乐路径不存在或不是有效的目录");
        }

        return songs;
    }

    // 构造复合键
    private String composeKey(String title, String artist) {
        return title + "###" + artist; // 使用特殊分隔符防止冲突
    }

    //给歌曲添加标签
//    public List<Song> addTags(List<Song> songs){
//
//    }
}